<?php

namespace App\Http\Controllers\Manage;

use App\Model\NewsCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;

use Validator;
use App\Model\News;
use App\Model\Manage;

class NewsController extends Controller
{
    //
    protected static $field = [
        'id' => '编号',
        'create_time' => '创建时间',
        'update_time' => '更新时间',
        'create_user' => '创建人',
        'update_user' => '更新人',
        'rank' => '权重',
        'title' => '标题',
        'category_id' => '新闻分类',
        'keywords' => '关键词',
        'top' => '置顶设置',
        'recomm' => '推荐设置',
        'picture' => '图片',
        'status' => '状态'
    ];

    public function index() {
        $obj = new News;
        $check_time = Input::get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');

        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }

        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }

        $data = $obj->paginate(10);
        $field = self::$field;
        return view('manage.news.index',compact('data','field','check_time','category','keyword','time','type','code'));
    }

    public function create() {
        $category = NewsCategory::where('status',1)->get();
        return view('manage.news.create',compact('category'));
    }

    /**
     * 添加数据
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request) {

        $savePath  = null;
        $input = $request->only('user_id','rank','category','title','keyword','description','picture','content');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'content' => 'required',
            'rank' => 'required',
            'keyword' => 'required',
            'description' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'content' => '内容',
            'rank' => '权重',
            'keyword' => '关键字',
            'description' => '描述'
        ];
//        dd($input);
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            if(News::where('title',$input['title'])->first()) {
                return redirect()->back()->withInput()->withErrors('文章名称已经存在');
            }
            else {
                if($request->hasFile('picture')) {
                    $file = $request->file('picture');
//                    dd($file);
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传文件有误！');
                    }
                    $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();

                    $destinationPath = 'upload/'.date('Y-m-d');  //public文件夹下新建storage/uploads文件夹
                    $file->move($destinationPath,$newFileName);
                    $savePath = date('Y-m-d') . '/' . $newFileName;
                }

                if(News::insert([
                    'rank' => $input['rank'],
                    'create_user' => $input['user_id'],
                    'category_id' =>$input['category'],
                    'title' => $input['title'],
                    'keywords' => $input['keyword'],
                    'picture' => $savePath,
                    'description' => $input['description'],
                    'content' => $input['content']
                ])) {
                    return Redirect::to("manage/news");
                }
                else  {
                    return redirect()->back()->withInput()->withErrors('添加失败');
                }
            }
        }
    }

    public function edit($id) {
        $news = News::find($id);
        return view('manage.news.edit',compact('news'));
    }

    /**
     * 更新数据
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request,$id) {

        $input = $request->only('rank','title','keywords','description','content','picture','user_id');
        if(empty($input['title']) || empty($input['content'])) {
            return redirect()->back()->withInput()->withErrors('缺少参数!');
        }
        if($request->hasFile('picture')) {
            $file = $request->file('picture');
            if(!$file->isValid()) {
                return redirect()->back()->withInput()->withErrors('上传文件有误！');
            }
            $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();

            $destinationPath = 'upload/'.date('Y-m-d');  //public文件夹下新建storage/uploads文件夹
            $file->move($destinationPath,$newFileName);
            $data['picture'] = date('Y-m-d') . '/' . $newFileName;
        }
        $data['rank'] = $input['rank'];
        $data['update_user'] = $input['user_id'];
        $data['title'] = $input['title'];
        $data['keywords'] = $input['keywords'];
        $data['description'] = $input['description'];
        $data['content'] = $input['content'];
        $map = News::where('id',$id)->update($data);
        if($map) {
            return Redirect::to('manage/news');
        }
        else {
            return redirect()->back()->withInput()->withErrors('更新失败!');
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function destroy()
    {

        $id = Input::Get('id');
        $res = News::where('id',$id)->delete();
        if($res){
            return [
                'code' => 100,
                'msg' => '删除成功！'
            ];
        }else{
            return [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
    }

    /**
     * 状态管理
     * @return array
     */
    public function status()
    {

        $id = Input::get('id');
        $status = Input::get('status');

        if($status == 1) {
            $del = News::where('id',$id)->update(['status'=>1,'update_user'=>session('user.id')]);
            $msg = '启用成功！';
        }else{
            $del = News::where('id',$id)->update(['status'=>0,'update_user'=>session('user.id')]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * 置顶操作
     * @return array
     */
    public function topStatus()
    {
        $id = Input::get('id');
        $category = Input::get('category');
        $status = Input::get('status');

        if($status == 1) {
            $map = News::where('top',1)->first();
            if($map) {
                return [
                    'code'=>103,
                    'msg'=> $map->title.'(ID：'.$map->id.')已置顶，请先取消!'
                ];
            }
            $del = News::where('id',$id)->update(['top'=>1,'update_user'=>session('user.id')]);
            $msg = '置顶成功！';
        }else{
            $del = News::where('id',$id)->update(['top'=>0,'update_user'=>session('user.id')]);
            $msg = '取消成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * 推荐操作
     * @return array
     */
    public function recommStatus()
    {
        $id = Input::get('id');
        $category = Input::get('category');
        $status = Input::get('status');
        $map = News::where('recomm',1)->count();
        if($status == 1) {
            if($map >= 6) {
                return [
                    'code'=>103,
                    'msg'=> '推荐文章已大于设定数量6篇，请先取消'
                ];
            }
            $del = News::where('id',$id)->update(['recomm'=>1,'update_user'=>session('user.id')]);
            $msg = '推荐成功！';
        }else{
            if($map == 1) {
                return [
                    'code'=>104,
                    'msg'=> '推荐文章不能为空'
                ];
            }
            $del = News::where('id',$id)->update(['recomm'=>0,'update_user'=>session('user.id')]);
            $msg = '取消成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }
}
